﻿var dynamicObject = function () {
    var self = this;

    self.bindingTypes = new Object();

    self.bindData = function (model, elementTobind) {
        elementTobind = elementTobind || document.getElementsByTagName("body")[0];

        //var elements = body[0].getElementsByTagName("*");
        elementTobind.dataContext = model;
        //bindDataInternal(model, elementTobind);
    };

    self.bindDataInternal = function (model, elementTobind) {

        if (elementTobind == null)
            return;

        self.applyBindingToControl(elementTobind, model);

        if (elementTobind.children.length > 0) {
            for (var i = 0; i < elementTobind.children.length; i++) {
                var element = elementTobind.children[i];
                self.bindDataInternal(model, element);
            }
        }
    };

    self.applyBindingToControl = function (element, model) {
        if (element == null || element.dataset == null)
            return;
        for (var bindingType in self.bindingTypes) {

            var bindingString = element.dataset[bindingType];
            if (bindingString !== undefined) {
                console.log("Appling binding " + bindingType + " on " + element.name);

                self.bindingTypes[bindingType].bind(element, bindingString, model);
            }
        }
    };

};

var _do = new dynamicObject();

var valueBindingType = function () {

    this.bind = function (element, bindingString, model) {
        var bindingPattern = new RegExp("{(.*)}");

        var extractedString = bindingPattern.exec(bindingString)[1];

        var splittedStrings = extractedString.split(',');

        if (splittedStrings.length == 1) {
            var bindingStr = splittedStrings[0].split(' ');

            var binding = bindingStr[0];
            var path = bindingStr[1];

            for (var property in model) {
                if (property == path) {
                    element.value = model[property];
                    break;
                }
            }
        }
    };
};

_do.bindingTypes.value = new valueBindingType();

